package www.nupter.org.njuptask.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import www.nupter.org.njuptask.R;
import www.nupter.org.njuptask.http.HttpCallBack;
import www.nupter.org.njuptask.http.HttpRequestUtil;
import www.nupter.org.njuptask.http.RequestUrl;
import www.nupter.org.njuptask.model.BaseInfo;
import www.nupter.org.njuptask.utils.DataUtils;


/**
 * A login screen that offers login via email/password.
 */
public class PublishQuestionActivity extends BaseActivity {
    private EditText titleEdit;
    private EditText contentEdit;
    private GridView gridView;
    private MyAdapter myAdapter;
    private static final int REQUEST_IMAGE = 2;
    private TextView textInfoView;
    private ProgressDialog progressDialog;

    private List<String> imgUrls = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_question);
        setTitle("提问题");
        setRightText("发布");
        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("正在发布问题，请等待");
        titleEdit = (EditText) findViewById(R.id.title);
        contentEdit = (EditText) findViewById(R.id.des);
        gridView = (GridView) findViewById(R.id.gridview);
        textInfoView = (TextView)findViewById(R.id.info_text);
        myAdapter = new MyAdapter();
        gridView.setAdapter(myAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Log.i("fang", "item" + i);
                switch (imgUrls.size()) {
                    case 0:
                        if (i == 0) {
                            startActivity();
                        }
                        break;
                }
            }
        });
    }

    public void startActivity() {
        Intent intent = new Intent(PublishQuestionActivity.this, MultiImageSelectorActivity.class);
        // 是否显示拍摄图片
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // 选择模式
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
        startActivityForResult(intent, REQUEST_IMAGE);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        textInfoView.setVisibility(View.GONE);
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == -1) {
                String la = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT).get(0);
                if (!imgUrls.contains(la))
                    imgUrls.add(la);
                myAdapter.notifyDataSetChanged();
            }
        }

    }

    @Override
    protected void HandleTitleBarEvent(TitleBar component, View v) {
        if (component == TitleBar.LEFT) {
            Intent intent=new Intent();
            intent.setClass(PublishQuestionActivity.this,RegisterActivity.class);
            startActivity(intent);
            finish();
        }else if (component==TitleBar.RightText){
            if (imgUrls.size()>=1){
                progressDialog.show();
                RequestParams requestParams=new RequestParams(RequestUrl.save_file);
                requestParams.setMethod(HttpMethod.POST);
                requestParams.setMultipart(true);
                requestParams.addParameter("file", new File(imgUrls.get(0)));
                HttpRequestUtil.postMethod(requestParams, BaseInfo.class, new HttpCallBack<BaseInfo>() {
                    @Override
                    public void success(BaseInfo data) {
                        saveQuestion(RequestUrl.base_image_url+data.getData());
                    }
                    @Override
                    public void erro(String res) {
                        progressDialog.dismiss();
                    }
                });
            }else {
                saveQuestion("1");
            }
        }
    }

    public void saveQuestion(String url){
       RequestParams requestParams=new RequestParams(RequestUrl.add_question);
        requestParams.addBodyParameter("title",titleEdit.getText().toString());
        requestParams.addBodyParameter("description","123");
        requestParams.addBodyParameter("content",contentEdit.getText().toString());
        requestParams.addBodyParameter("userId", DataUtils.getPreferences("userId","1"));
        requestParams.addBodyParameter("file",url);
        HttpRequestUtil.postMethod(requestParams, BaseInfo.class, new HttpCallBack<BaseInfo>() {
            @Override
            public void success(BaseInfo data) {
                progressDialog.dismiss();
                finish();
            }
            @Override
            public void erro(String res) {
                progressDialog.dismiss();
               BaseToast(res);
            }
        });
    }

    public class MyAdapter extends BaseAdapter {
        private LayoutInflater layoutInflater;

        public MyAdapter() {
            layoutInflater = LayoutInflater.from(PublishQuestionActivity.this);
        }

        @Override
        public int getCount() {
            if (imgUrls.size() <= 2)
                return 1 + imgUrls.size();
            else
                return 3;
        }

        @Override
        public Object getItem(int i) {
            return i;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view = layoutInflater.inflate(R.layout.gridview_item, viewGroup, false);
            ImageView imageView = (ImageView) view.findViewById(R.id.img);
            if (imgUrls.size() == 0) {
                imageView.setImageResource(R.drawable.icon_camera);
            } else {
                if (imgUrls.size() <= 2) {
                    if (i == imgUrls.size()) {
                        imageView.setImageResource(R.drawable.icon_camera);
                    } else {
                        HttpRequestUtil.initLocalImage(imageView, imgUrls.get(i));
                    }
                } else {
                    Log.i("fang", imgUrls.get(i));
                    HttpRequestUtil.initLocalImage(imageView, imgUrls.get(i));
                }
            }

            return view;
        }
    }
}

